<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use http\Params;
use think\Db;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use think\Config;
use addons\alioss\library as oss;
/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shop;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','label'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $k=>$row) {
                
                $row->getRelation('user')->visible(['username']);
				$row->getRelation('label')->visible(['name']);
				$goods = Db::name('goods')->where('shop_id',$row['id'])->order('id desc')->find();
				if(!empty($goods))
				{
				    $list[$k]['view'] = $goods['view'];
				}else{
				    $list[$k]['view'] = 0;
				}
				$order= Db::name('order')->where(['shop_id'=>$row['id'],'paystate'=>1])->count();
				$list[$k]['pay_num'] = $order;
				$orders= Db::name('order')->where(['shop_id'=>$row['id'],'orderstate'=>1])->count();
				$list[$k]['hx_num'] = $orders;
				$list[$k]['qrcode'] = serverUrl().$row['qrcode'];

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
     /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // $result = $this->model->allowField(true)->save($params);
                    $params['createtime'] = time();
                    $result = Db::name('shop')->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                if ($result !== false) {
                    $qrcode = $this->wxappUrl($result);
                    //$str = substr($qrcode,1);
        
                    Db::name('shop')->where('id',$result)->update(['qrcode'=>$qrcode]);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    
     /**
     *生成小程序二维码
     * */
    public function wxappUrl($id){
        
        header('content-type:text/html;charset=utf-8');
        
        $config = get_addon_config('epay');
        $appid = $config['wechat']['app_id'];
        $secret =$config['wechat']['app_secret'];
        //$appid = "wx00e6c59afbd831d6";
       // $secret = "0512f5e03e31043ede5f8da14d0c32cc";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $weix = file_get_contents($url);//获得网页输出
        $obj=json_decode($weix,true);//解码
        $access_token= $obj['access_token'];//网页授权接口调用凭证
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
        //$data = json_encode(['action_name'=>"QR_LIMIT_STR_SCENE","action_info"=>['shop_id'=>["shop_id"=>$id]]]);
        $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"shop_id": '.$id.'}}}';

        $wx = $this->httpRequest($url,$data);
        return $wx; 
    }
    public  function httpRequest($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过ssl检测
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里，那加上这句。
        $res = curl_exec($ch);
        /////
        $res =  json_decode($res,true);
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$res['ticket'];
        $weix = file_get_contents($url);//获得网页输出
        //$obj=json_decode($weix,true);//解码
        /// ///
        //var_dump($weix);exit;
        //$name = "./qrcode/".time().".png";
       // params
        //\addons\alioss\index\params::

        $ur = '/assets/img/qrcode/'.time().".png";
        $name = ROOT_PATH . 'public'.$ur;
        file_put_contents($name,$weix);
        curl_close($ch);
        //oss\Auth::params($ur,md5($ur));
        return $ur;
    }

    
    public function export()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');

            //$excel = new PHPExcel();
            $spreadsheet = new Spreadsheet();

            $spreadsheet->getProperties()
                ->setCreator("Storecode")
                ->setLastModifiedBy("Storecode")
                ->setTitle("店铺码")
                ->setSubject("Subject");
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);
            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $line = 1;

            //设置过滤方法
            $this->request->filter(['strip_tags']);

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($whereIds)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($whereIds)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            
            $first = array_keys($list[0]);
            foreach ($first as $index => $item) {
                $worksheet->setCellValueByColumnAndRow($index, 1, __($item));
            }
            
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(__DIR__ . '/muban/export.xls');  //读取模板
            $worksheet = $spreadsheet->getActiveSheet();     //指向激活的工作表
            $worksheet->setTitle('店铺码导出');

            for($i=0;$i<$total;++$i){ 
                //向模板表中写入数据
                // $worksheet->setCellValue('A1', '模板测试内容');   //送入A1的内容
                $worksheet->getCell('B2')->setValue($result['rows'][$i]['shop_name']);   
                $worksheet->getCell('d2')->setValue($result['rows'][$i]['logo']);  
                // $worksheet->getCell('f2')->setValue($result['rows'][$i]['hobbydata']);  //爱好
                // $worksheet->getCell('b3')->setValue($result['rows'][$i]['title']);  //标题
                // $worksheet->getCell('b4')->setValue($result['rows'][$i]['content']);  //内容
                
                
                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
                //下载文档
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'. date('Y-m-d').'_export'.'.xlsx"');
                header('Cache-Control: max-age=0');
                $writer = new Xlsx($spreadsheet);
                $writer->save('php://output');
            }        

            return;
        }
    }

}
